package com.dc.base.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.alibaba.fastjson.JSONObject;
import com.dc.common.model.BaseModel;

/**
 * 
 * <h2>全局异常处理器</h2>
 * 
 * @ClassName: BusinessExceptionResolve
 * @author Enzo
 * @date 2018年1月10日 上午9:37:03
 */
public class BusinessExceptionResolve extends SimpleMappingExceptionResolver implements HandlerExceptionResolver {
	private static Logger logger = Logger.getLogger(BusinessExceptionResolve.class);

	/**
	 * 
	 * <h3></h3>
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 *            系统抛出的异常
	 * @return
	 * @author Enzo
	 * @date 2018年1月10日 上午9:40:10
	 */

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		String viewName = determineViewName(ex, request);
		//response.setHeader("Content-Type", "text/plain; charset=utf-8");
		//response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		// 如果异常类型是自定义的异常，直接去除异常页面展示
		BusinessException businessExcetion = null;
		if (ex instanceof BusinessException) {
			businessExcetion = (BusinessException) ex;
		} else {
			// 如果异常类型不是系统自定义异常，构造一个自定义的异常类型（信息为‘系统异常’）
			businessExcetion = new BusinessException(-1,"系统异常,请联系管理员");
		}
		try {
			//把返回的错误信息放入baseModel并转换成json
			BaseModel baseModel = new BaseModel();
			baseModel.setCode(businessExcetion.getCode());
			baseModel.setMessage(businessExcetion.getMessage());
			baseModel.setMessageEX(ex.toString());
			response.getWriter().print(JSONObject.toJSON(baseModel).toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
//		if (viewName != null) {
//			Integer statusCode = determineStatusCode(request, viewName);
//			if (statusCode != null) {
//				applyStatusCodeIfPossible(request, response, statusCode);
//			}
//			System.out.println("JSP格式返回" + viewName);
//			return getModelAndView(viewName, ex, request);
//		}
//		try {
//			//此处可以改为返回错误信息为baseModel
//			PrintWriter writer = response.getWriter();
//			writer.write(new String(message.getBytes()));
//			writer.flush();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		return null;
	}


}
